#include <windows.h>
#include <stdio.h>

#include <iostream>
using namespace std;

int main(int argc, char ** argv)
{
if (argc != 2)
{
	cout << "	USAGE: TcpEchoServer port" << endl << endl;
	return 0;
}

int port = atoi(argv[1]);
WSADATA wsaData;
WSAStartup(MAKEWORD(2,2), &wsaData);

SOCKET ListenSocket;
ListenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (ListenSocket == INVALID_SOCKET) 
{
	printf("Error at socket(): %ld\n", WSAGetLastError());
	WSACleanup();
	return -1;
}


sockaddr_in service;
service.sin_family = AF_INET;
service.sin_addr.s_addr = inet_addr( "127.0.0.1" );
service.sin_port = htons( port );


if (bind( ListenSocket,(SOCKADDR*) &service, sizeof(service)) == SOCKET_ERROR)
{
	printf("bind() failed.\n");
    closesocket(ListenSocket);
	WSACleanup();
    return -1;
}

if (listen( ListenSocket, 1 ) == SOCKET_ERROR)
{
	printf("Error listening on socket.\n");
	WSACleanup();
	return -1;
}

SOCKET AcceptSocket;


while(1) 
{
	AcceptSocket = SOCKET_ERROR;
	while( AcceptSocket == SOCKET_ERROR ) 
	{
		AcceptSocket = accept( ListenSocket, NULL, NULL );
	}
	printf("Client connected.\n");
	ListenSocket = AcceptSocket;
	break;
}


unsigned long one = 1;
ioctlsocket(ListenSocket, FIONBIO, &one);

char r;
char buf[100];
int pos = 0;
int res;
while (true)
{
	Sleep(5);
	res = ::recv(ListenSocket, buf, 100, 0);		
	if (res == 0) break;
	if (res == -1)
	{
		if (WSAGetLastError()==WSAEWOULDBLOCK) continue;
			else break;
	}
	res = ::send(ListenSocket, buf, res, 0);
	if (-1 == res)
		break;
	
}

return 0;
}